﻿using Pathfinding;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

namespace Elves
{
    public class ElvesMoveAI
    {
        private Path path;
        private Seeker seeker;

        private int currentWayPoint = 0;
        private bool reachedEndOfPath;

        float nextWayPointDistance = 1f;

        Rigidbody2D moveRd;

        ElvesBody elvesBody;

        private Transform m_target;

        float moveClose = 5f;

        Timer timer;

        public ElvesMoveAI(ElvesBody body,Seeker s)
        {
            elvesBody = body;
            seeker = s;
            timer = new Timer(0.5f, true, elvesBody.ElvesData, UpdatePath);
        }

        public void StartPath()
        {
            timer.Start();
        }

        public void EndPath()
        {
            timer.End();
        }

        public void Move(Transform target, float speed,float minDis)
        {
            m_target = target;
            if (path == null)
                return;
            if (currentWayPoint >= path.vectorPath.Count)
            {
                reachedEndOfPath = true;
                return;
            }
            else
            {
                reachedEndOfPath = false;
            }

            
            Vector2 direction = ((Vector2)path.vectorPath[currentWayPoint] - moveRd.position).normalized;
            Vector2 force = direction * speed * Time.deltaTime;

            if (Vector2.Distance(target.position, moveRd.position) <= moveClose)
                force = force / 3;

            moveRd.AddForce(force);
            
            if (Vector2.Distance(target.position, moveRd.position) <= minDis)
            {
                moveRd.velocity = Vector2.zero;
            }

            float distance = Vector2.Distance(moveRd.position, path.vectorPath[currentWayPoint]);
            if (distance < nextWayPointDistance)
            {
                currentWayPoint++;
            }
        }

        public void UpdatePath()
        {
            if (m_target == null)
            {
                return;
            }
            if (seeker.IsDone())
                seeker.StartPath(moveRd.position, m_target.position, OnPathCompete);
        }

        void OnPathCompete(Path p)
        {
            if (!p.error)
            {
                path = p;
                currentWayPoint = 0;
            }
        }
    }
}

